package com.yiper.util;

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

public class PasswordHelper {
	
	private static final int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
    private static final int PBKDF2SubkeyLength = 256 / 8; // 256 bits
    private static final int SaltSize = 128 / 8; // 128 bits
    
	public static String hashPassword(String password) throws Exception{
        if (password == null) {
            throw new IllegalArgumentException("password is null");
        }
        // Produce a version 0 (see comment above) password hash.
        byte[] salt = SecureRandom.getSeed(SaltSize);
        Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, salt, PBKDF2IterCount);
        byte[] subkey = rfc.getBytes(PBKDF2IterCount);
        byte[] outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength];
        System.arraycopy(salt, 0, outputBytes, 1, SaltSize);
        System.arraycopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength);
        return Base64.getEncoder().encodeToString(outputBytes);
    }
	
	public static boolean VerifyHashedPassword(String hashedPassword, String password) throws Exception{
        if (hashedPassword == null) {
            throw new IllegalArgumentException("hashedPassword is null");
        }
        if (password == null) {
        	throw new IllegalArgumentException("password is null");
        }
        byte[] hashedPasswordBytes = Base64.getDecoder().decode(hashedPassword);
        // Verify a version 0 (see comment above) password hash.
        if (hashedPasswordBytes.length != (1 + SaltSize + PBKDF2SubkeyLength) || hashedPasswordBytes[0] != 0x00) {
            // Wrong length or version header.
            return false;
        }

        byte[] salt = new byte[SaltSize];
        System.arraycopy(hashedPasswordBytes, 1, salt, 0, SaltSize);
        byte[] storedSubkey = new byte[PBKDF2SubkeyLength];
        System.arraycopy(hashedPasswordBytes, 1 + SaltSize, storedSubkey, 0, PBKDF2SubkeyLength);
        
        Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, salt, PBKDF2IterCount);
        byte[] generatedSubkey = rfc.getBytes(PBKDF2SubkeyLength);
        return Arrays.equals(storedSubkey, generatedSubkey);
    }
	
//	@SuppressWarnings("static-access")
//	public static void main(String[] args) throws Exception{
//		PasswordHelper p = new PasswordHelper();
//		//AIRSTn4vpaTSKraWbbJw2+El8Ci0IASz1imneHVd32BK0dTfVYheU8ap7daM8q9YTQ==
//		//ALTR/+13nvkrEi/sbmVDptB+AT3KwMkelnZUMZvXGv8wR5YUXPBSZwbj1NsJzbGY7w==
//
//		
//	}

    public static void main(String args[]) throws Exception {
        System.err.println(hashPassword("123"));
    }
}
